import tkinter as tk
import random
# 加载本地数据
import chat as ch
from tkinter import scrolledtext

# 初始化窗口
root = tk.Tk()
root.title("鞋店通用聊天机器人")

# 设置窗口大小
root.geometry("400x400")

# 创建聊天记录显示框
talk = scrolledtext.ScrolledText(root, wrap=tk.WORD, width=40, height=10)
talk.grid(row=0, column=0, columnspan=2, padx=10, pady=10)

# 创建输入框
input = tk.Entry(root, width=30)
input.grid(row=1, column=0, padx=10, pady=10)

# 创建发送按钮
send_button = tk.Button(root, text="发送", command=lambda: send())
send_button.grid(row=1, column=1, padx=10, pady=10)

# 初始化聊天记录和数据
TALK = []
QA = []
Q = []
A = []
# 加载数据，这里只是一种基本的数据，当然你也可以将本次成功的聊天记录追加到数据中
DATA = ch.DATA

# 转换器模型用于生成题型
def transformer(data):
    for d in data:
        qa = ''
        q = []
        a = []
        for i in range(len(d)):
            key = d[i]
            if i % 2 == 0:
                qa += '_'
                a.append(key)
            else:
                qa += key
                q.append(key)
        QA.append(qa)
        Q.append(q)
        A.append(a)

# 开始进行转换
transformer(DATA)

# 客户：发送消息
def send():
    str = input.get()
    if str!= '':
        # 显示并追加聊天记录
        talk.insert(tk.END, '你：' + str + '\n')
        TALK.append(str)
        robot()

# 机器人：输出权重最高的关键词
def robot():
    global TALK, A
    a_s = count(A)
    # 根据概率选择回答
    sum = 0
    borders = []
    robots = []
    for a in a_s:
        sum += a_s[a]
        robots.append(a)
        borders.append(sum)
    border = random.random() * sum - 1
    for b in range(len(borders)):
        if border < borders[b]:
            # 显示并追加聊天记录
            talk.insert(tk.END, '机器人：' + robots[b] + '\n')
            TALK.append(robots[b])
            break

# 开始新话题
def reset():
    global TALK
    TALK = []
    robot()

# 客户满意就将本次聊天追加到话术库中
def good():
    DATA.append(TALK)
    # 这里假设DATA是全局变量或者有其他方式存储
    # 实际应用中可能需要将DATA保存到文件或数据库中

# 词频统计
def count(words):
    global TALK
    ls = len(TALK) // 2
    think = {}
    for word in words:
        s = word[ls] if ls < len(word) else '好的'
        if s in think:
            think[s] += 1
        else:
            think[s] = 1
    return think

# 先计算两秒钟再主动询问
root.after(1000, robot)

# 运行主循环
root.mainloop()